/**
* 版权所有:版权所有(C) 2020，卓信科技
* 系统名称:FOL2020-财务在线
* 文件名称:HttpClientUtil.java
* 模块名称:HttpClientUtil
* 创建日期:2020年5月19日
* 作        者:Baisong
* 内容摘要:连接
*/
package com.zx.emanage.util.gen;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
 * 类  名  称:HttpClientUtil
 *
 * 内容摘要:连接
 *
 * 作        者:Baisong
 */
public class HttpClientUtil {

	private final static Integer TIMEOUT = 5 * 60 * 1000;

	public static String post(String url, List<NameValuePair> nvps) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
		if (nvps == null) {
			nvps = new ArrayList<NameValuePair>();
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		CloseableHttpClient httpclient = HttpClients.createDefault();
		RequestConfig rc = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
		httpPost.setConfig(rc);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String str = EntityUtils.toString(entity);
				EntityUtils.consume(entity);
				return str;
			} else {
			}
		} finally {
			response.close();
			httpclient.close();
		}
		return "";
	}

	public static String post(String url, String text) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
		EntityBuilder eb = EntityBuilder.create();
		eb.setContentEncoding("utf-8");
		if (text != null) {
			eb.setText(text);
		}
		httpPost.setEntity(eb.build());
		CloseableHttpClient httpclient = HttpClients.createDefault();
		RequestConfig rc = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
		httpPost.setConfig(rc);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String str = EntityUtils.toString(entity);
				EntityUtils.consume(entity);
				return str;
			} else {
			}
		} finally {
			response.close();
			httpclient.close();
		}
		return "";
	}

	public static <T> T post(String url, List<NameValuePair> nvps, Class<T> clazz)
			throws ClientProtocolException, IOException {
		String result = post(url, nvps);

		return JacksonMapper.getInstance().readValue(result, clazz);
	}

}
